"use strict";

var Router = require('koa-router');
var config = require('../../config/index.js');
var appUtil = require('../../common/app_utils.js');

//
var __pathPrefix = config.testApiPre + '/v1';
appUtil.appLog('router:' + __pathPrefix);
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

router.get('**', function*() {
  console.log('hello %s %s', this.method, this.url);
  this.body = 'hello, its works abc xxx';
});

router.post('/base64test', function*() {
  //console.log(this.request.body.fields.base64);
  var str = this.request.body.fields.base64;
  var imageBuffer = decodeBase64Image(str);
  writeToFile(imageBuffer);

  this.body = this.request.body.fields.base64;
});


function decodeBase64Image(dataString) {
  var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
    response = {};
  if (matches.length !== 3) {
    return new Error('Invalid input string');
  }
  response.type = matches[1];
  response.data = new Buffer(matches[2], 'base64');
  return response;
}

var fs = require('fs');
var path = require('path');
function writeToFile(imageBuffer) {
  var savePath = path.join(config.cwd, '/upload_tmp/from_base64.jpg');
  //fs.writeFile(savePath, imageBuffer.data, function (err) {
  //  if (err) console.log('save error', err);
  //});
  fs.writeFileSync(savePath, imageBuffer.data);
}
